<?php
namespace Home\Controller;

use Utuo\WechatActivityController;

class BoxController extends WechatActivityController
{
    // activity config
    private $activity;
    
    // host info
    private $hostInfo;
    
    // register info
    private $registerInfo;
    
    // init
    public function _initialize()
    {
        layout('Box/layout');
    }
    
    // get activity info
    private function initInfo()
    {
        // 活动信息
        $this->activity = M('WechatActivityBox')->find($this->aid);
        $this->activity['prize'] = unserialize($this->activity['prize']);
        if ( !$this->activity['status'] ) {
        	header("Content-Type:text/html;charset=utf-8");
        	exit("活动未开始，敬请期待。。");
        }
        
        // 当前用户发起活动信息
        $this->hostInfo = M('WechatActivityBoxHost')->where(array(
            'cid' => $this->cid,
            'aid' => $this->aid,
            'uid' => $this->userInfo['id']
        ))->find();
        
        // 活动分享地址
        $this->activity['shareUrl'] = $this->getFullUrl(array(
            'cid' => $this->cid,
            'aid' => $this->aid,
            'fid' => $this->userInfo['id']
        ));
        
        // 好友参与地址
        $this->activity['playUrl'] = $this->getFullUrl(array(
            'cid' => $this->cid,
            'aid' => $this->aid,
            'fid' => $this->userInfo['id'],
            'hid' => $this->hostInfo['id']
        ), 'openBox');
    }
    
    // 活动主页
    public function indexAction()
    {
        $this->initInfo();
        
        // 视图
        $this->assign('userInfo', $this->userInfo);
        $this->assign('activity', $this->activity);
        $this->assign('hostInfo', $this->hostInfo);
        $this->display();
    }
    
    // 选择盒子
    public function getBoxAction()
    {
        $this->initInfo();
        
        // 视图
        $this->assign('userInfo', $this->userInfo);
        $this->assign('activity', $this->activity);
        $this->assign('hostInfo', $this->hostInfo);
        $this->display();
    }
    
    // 我的盒子页面
    public function myBoxAction()
    {
        $this->initInfo();
        
        $this->hostInfo['diff'] = $this->activity['openCount'] - $this->hostInfo['openCount'];
        
        if ($this->hostInfo['diff'] <= 0) {
            $data = array(
                'cid' => $this->cid,
                'aid' => $this->aid,
                'uid' => $this->userInfo['id'],
                'hid' => $this->hostInfo['id']
            );
            $prizeInfo = M('WechatActivityBoxPrize')->where($data)->find();
            if (! empty($prizeInfo)) {
                $this->activity['sharePrizeUrl'] = $this->getFullUrl(array(
                    'cid' => $this->cid,
                    'aid' => $this->aid,
                    'fid' => $this->userInfo['id'],
                    'hid' => $this->hostInfo['id']
                ), 'sharePrize');
                $registerInfo = M('WechatActivityBoxRegister')->where($data)->find($data);
            }
        }
        
        $playList = M('WechatActivityBoxPlay p')->join("LEFT JOIN __WECHAT_ACTIVITY_USER__ u ON p.uid=u.id")
            ->field("p.*, u.nickname")
            ->where(array(
                    'p.cid' => $this->cid,
                    'p.aid' => $this->aid,
                    'p.hid' => $this->hostInfo['id']
                ))
            ->select();
        
        // 视图
        $this->assign('playList', $playList);
        $this->assign('prizeInfo', $prizeInfo);
        $this->assign('registerInfo', $registerInfo);
        $this->assign('userInfo', $this->userInfo);
        $this->assign('activity', $this->activity);
        $this->assign('hostInfo', $this->hostInfo);
        $this->display();
    }
    
    // 分享中奖页面
    public function sharePrizeAction()
    {
        $this->initInfo();
        
        $data = array(
            'cid' => $this->cid,
            'aid' => $this->aid,
//             'uid' => $this->userInfo['id'],
            'hid' => I('hid',0,'intval')
        );
        $prizeInfo = M('WechatActivityBoxPrize')->where($data)->find();
        
        // 视图
        $this->assign('prizeInfo', $prizeInfo);
        $this->assign('userInfo', $this->userInfo);
        $this->assign('activity', $this->activity);
        $this->assign('hostInfo', $this->hostInfo);
        $this->display();
    }
    
    // 打开盒子
    public function openBoxAction()
    {
        $this->initInfo();
        
        $hid = I('hid', 0, 'intval');
        
        $data = array(
            'h.cid' => $this->cid,
            'h.aid' => $this->aid,
            'h.id' => $hid
        );
        
        $model = M('WechatActivityBoxHost h');
        $model->join('LEFT JOIN __WECHAT_ACTIVITY_USER__ u ON h.uid=u.id');
        $model->field('h.*,u.nickname, u.headimgurl');
        $openInfo = $model->where($data)->find();
        $openInfo && $openInfo['diff'] = $this->activity['openCount'] - $openInfo['openCount'];
        
        // 视图
        $this->assign('openInfo', $openInfo);
        $this->assign('userInfo', $this->userInfo);
        $this->assign('activity', $this->activity);
        $this->assign('hostInfo', $this->hostInfo);
        $this->display();
    }
    
    // 登录中奖用户
    public function registerAction()
    {
        $m = M('WechatActivityBoxRegister');
        
        // 检查是否已经登记
        $count = $m->where(array(
            'cid' => $this->cid,
            'aid' => $this->aid,
            'uid' => I('uid', 0, 'intval'),
            'hid' => I('hid', 0, 'intval')
        ))->count();
        $count === false && $this->ajaxError('网络错误，请重试！(001)');
        $count > 0 && $this->ajaxError('您已经登记过了~');
        
        // 检查登记人数是否已经超过活动限制人数
        $prizeCount = M('WechatActivityBox')->where(array(
            'cid' => $this->cid,
            'id' => $this->aid
        ))->getField("prizeCount");
        $prizeCount === false && $this->ajaxError('网络错误，请重试！(002)');
        $registerCount = $m->where(array(
            'cid' => $this->cid,
            'aid' => $this->aid
        ))->count();
        $registerCount === false && $this->ajaxError('网络错误，请重试！(003)');
        $registerCount >= $prizeCount && $this->ajaxError('很遗憾，登记人数已经超过奖品数量~');
        
        C("TOKEN_ON", false);
        
        if ($m->create()) {
            $m->createTime = time();
            if ($m->add()) {
                $this->ajaxSuccess('登记成功，请等待工作人员与您联系~');
            } else {
                $this->ajaxError('网络错误，请再试一次~');
            }
        } else {
            $this->ajaxError('提交数据错误，请检查重试~' . $m->getError());
        }
    }
    
    // 活动规则
    public function ruleAction()
    {
        $this->initInfo();
        $this->assign('activity', $this->activity);
        $this->display();
    }
    
    // 打开盒子，领取奖品，ajax请求
    public function ajaxGetPrizeAction()
    {
        $uid = I('uid', 0, 'intval');
        $hid = I('hid', 0, 'intval');
        $data = array(
            'cid' => $this->cid,
            'aid' => $this->aid,
            'uid' => $uid,
            'hid' => $hid
        );
        $model = M('WechatActivityBoxPrize');
        if ($model->where($data)->find()) {
            $this->ajaxError('您已经领取过奖品了哦~');
        }
        $prizeLevel = $this->getPrizeLevel();
        $data['prizeLevel'] = $prizeLevel;
        $data['prizeName'] = empty($this->activity['prize'][$prizeLevel]['name']) ? '' : $this->activity['prize'][$prizeLevel]['name'];
        $prizeCode = empty($this->activity['prize'][$prizeLevel]['code']) ? null : explode("\n", $this->activity['prize'][$prizeLevel]['code']);
        $id = $model->add($data);
        if ($id) {
            if ($prizeCode) {
                $count = $model->where(array(
                    'cid' => $this->cid,
                    'aid' => $this->aid,
                    'prizeLevel' => $prizeLevel,
                    'id' => array(
                        'lt',
                        $id
                    )
                ))->count();
                $code = empty($prizeCode[$count]) ? null : $prizeCode[$count];
                if ($code) {
                    $code = trim($code);
                    $model->where("id=%d", $id)->setField('prizeCode', $code);
                    // 把红包序列码绑定到用户
                    $userId = $this->bindCode($uid, $code);
                    if ($userId) {
                        $this->ajaxSuccess('领取奖品成功，红包已经发送到您的账户！');
                    } else {
                        $this->ajaxError('网络错误');
                    }
                } else {
                    $this->ajaxError('很遗憾，你来晚了，红包已经发完了');
                }
            }
            $this->ajaxSuccess('领取奖品成功', $id);
        } else {
            $this->ajaxError('领取奖品失败，请重试~');
        }
    }
    
    // 绑定红包序列码和用户
    private function bindCode($uid, $code)
    {
        $userId = M('WechatUser u')->join("LEFT JOIN __WECHAT_ACTIVITY_USER__ au ON au.openid=u.openId")
            ->where("au.id=%d", $uid)
            ->getField("u.id");
        if (empty($userId)) {
            return false;
        }
        $data = array(
            'uid' => $userId,
            'efficacy'=>1,
            'takeAwayTime' => time()
        );
        $result = M('DistributionShopRedPacket')->where(array(
            'cid' => $this->cid,
            'code' => $code
        ))->save($data);
        if ($result === false) {
            return false;
        }
        return $userId;
    }
    
    // 登记信息
    public function ajaxRegisterAction()
    {
        C('TOKEN_ON', false);
        $model = M('WechatActivityBoxRegister');
        if ($model->create()) {
            if ($model->add()) {
                $this->ajaxSuccess('登记信息成功');
            } else {
                $this->ajaxError('登记信息失败');
            }
        } else {
            $this->ajaxError('信息填写错误，请重试~');
        }
    }
    
    // 领取盒子，ajax请求，不经过跳转
    public function ajaxGetBoxAction()
    {
        $boxId = I('boxId', 1, 'intval');
        $uid = I('uid', 0, 'intval');
        $data = array(
            'cid' => $this->cid,
            'aid' => $this->aid,
            'uid' => $uid
        );
        $this->hostInfo = M('WechatActivityBoxHost')->where($data)->find();
        if ($this->hostInfo) {
            $this->ajaxError("每个用户只能领取一个盒子哦");
        }
        $data['boxId'] = $boxId;
        $hostId = M('WechatActivityBoxHost')->add($data);
        if ($hostId) {
            $this->ajaxSuccess("领取盒子成功", array(
                'hostId' => $hostId
            ));
        } else {
            $this->ajaxError("领取盒子失败，请重新试试吧！");
        }
    }
    
    // 帮忙开盒子，ajax请求，不经过跳转
    public function ajaxOpenBoxAction()
    {
        $uid = I('uid', 0, 'intval');
        $hid = I('hid', 0, 'intval');
        $hostUserId = M('WechatActivityBoxHost')->where(array(
            'id' => $hid
        ))->getField('uid');
        $uid == $hostUserId && $this->ajaxError('自己不能为自己拆盒子哦~');
        $data = array(
            'cid' => $this->cid,
            'aid' => $this->aid,
            'uid' => $uid,
            'hid' => $hid
        );
        $playInfo = M('WechatActivityBoxPlay')->where($data)->find();
        if ($playInfo) {
            $this->ajaxError("您已经帮他拆过盒子了哦");
        }
        $playId = M('WechatActivityBoxPlay')->add($data);
        if ($playId) {
            M('WechatActivityBoxHost')->where(array(
                'cid' => $this->cid,
                'aid' => $this->aid,
                'id' => $hid
            ))->setInc("openCount", 1);
            $this->ajaxSuccess("成功的帮助了朋友拆开盒子^_^");
        } else {
            $this->ajaxError("拆盒子失败，请重新试试吧！");
        }
    }
    
    // 取得奖品信息
    private function getPrizeLevel()
    {
        $this->initInfo();
        $prize = $this->activity['prize'];
        $dict = array();
        foreach ($prize as $k => $v) {
            $dict = array_pad($dict, count($dict) + intval($v['percent']), $k);
        }
        $dict = array_pad($dict, 100, - 1);
        $level = $dict[array_rand($dict)];
        if ($level >= 0) {
            $count = M('WechatActivityBoxPrize')->where(array(
                'cid' => $this->cid,
                'aid' => $this->aid
            ))->count();
            $count >= $prize[$level]['total'] && $level = - 1;
        }
        return $level;
    }
}